//
//  DealerController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/11/28.
//  Copyright © 2018 小河. All rights reserved.
//

#import "DealerController.h"

@interface DealerController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UILabel *leftHeaderLabel;
@property (nonatomic, strong) UILabel *totalHeaderLabel;

@property (nonatomic, strong) NSMutableDictionary *attributesDic;
@property (nonatomic, copy) NSString *nextPageInfo;

@end

@implementation DealerController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor orangeColor];
    self.bgNavView.hidden = YES;
    [self createTableView];
    
    self.dataArray = [NSMutableArray array];
    [self httpRequestData];//
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *isReload = USER_DEFAULTS_GET(@"isReload");
    if ([isReload isEqualToString:@"1"])
    {
        USER_DEFAULTS_SAVE(@"", @"isReload");
        [self httpRequestNewData];
    }
}

#pragma mark - 请求已上架商品
- (void)httpRequestData
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:@"false" forKey:@"isPlatform"];//是否平台商品
    [dic setValue:@"1" forKey:@"itemState"];//商品状态
    if (NOEmptyStr(self.nextPageInfo))
    {
        [dic setValue:self.nextPageInfo forKey:@"nextPageInfo"];//翻页
    }
    __weak DealerController *myself = self;
    [HttpRequest formPostPath:SearchGoods_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
    {
//        NSLog(@"已上架商品--%@",Data);
        if (msgModel.status == 200)
        {
            myself.attributesDic = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)Data[@"attributes"]];
            
            
            NSDictionary *result = (NSDictionary *)Data[@"result"];
            myself.nextPageInfo = result[@"nextPageInfo"];
            NSArray *currentPageResult = result[@"currentPageResult"];
//            NSLog(@"currentPageResult--%@",currentPageResult);
//            NSLog(@"nextPageInfo--%@",myself.nextPageInfo);
           
            NSError *error;
            if (currentPageResult.count == 0|| [currentPageResult[0] allKeys].count == 0)
            {
                [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                for (NSDictionary *dic in currentPageResult)
                {
                    MainModel *model = [[MainModel alloc] initWithDictionary:dic error:&error];
                    [myself.dataArray addObject:model];
                    NSLog(@"已上架商品dic--%@",dic);
                }
            }
            [myself.myTableView.mj_header endRefreshing];
            [myself.myTableView.mj_footer endRefreshing];
            myself.myTableView.tableHeaderView = [self tableViewHeader];
            [myself.myTableView reloadData];
        }
        else {
            [myself.myTableView.mj_header endRefreshing];
            [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
        }
        
    }];
}

#pragma mark - 下拉刷新
- (void)httpRequestNewData
{
    [self.dataArray removeAllObjects];
    self.nextPageInfo = nil;
    [self httpRequestData];//
}

#pragma mark - 上拉加载更多
- (void)httpMoreData
{
    if (IsEmptyStr(self.nextPageInfo))
    {
        [self ShowHUDWithMessage:@"无更多已上架商品"];
        [self.myTableView.mj_footer endRefreshingWithNoMoreData];
    }else {
        [self httpRequestData];//
    }
}

- (void)createTableView
{
    if (@available(iOS 11.0, *))
    {
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-46-40-TopBarHeight_xs-BottomHeight_xs-TopBarHeight) style:UITableViewStylePlain];
    }
    else {
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-46-40-TopBarHeight-BottomHeight-TopBarHeight) style:UITableViewStylePlain];
    }
    self.myTableView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    [self.view addSubview:self.myTableView];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.sectionHeaderHeight = 0.01f;
    self.myTableView.sectionFooterHeight = 10.f;
    self.myTableView.tableFooterView = [self tableViewFoot];
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(httpRequestNewData)];
    self.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(httpMoreData)];
    [TTKUtil setAutomaticallyAdjustsScrollViewInsetsWidth:self.myTableView withView:self];
    [self.myTableView registerClass:[StorageShoppingCell class] forCellReuseIdentifier:@"StorageShoppingCell"];
}

- (UIView *)tableViewHeader
{
    UIView *view = [[UIView alloc] init];
    NSInteger amountOne = [(NSString *)self.attributesDic[@"amountOne"] integerValue];
    NSInteger amountTwo = [(NSString *)self.attributesDic[@"amountTwo"] integerValue];
    NSInteger totalCount = [(NSString *)self.attributesDic[@"totalCount"] integerValue];
    if (totalCount > 0)
    {
        view.frame = CGRectMake(0, 0, SCREENWIDTH, 48);
    }else {
        view.frame = CGRectMake(0, 0, SCREENWIDTH, 0);
    }
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    [view addSubview:titleLabel];
    titleLabel.frame = CGRectMake(15, 18, 260, 12);
    titleLabel.textColor = RGBACOLOR(153, 153, 153, 1);
    titleLabel.textAlignment = 0;
    titleLabel.font = FontWithSize(12);
    titleLabel.text = [NSString stringWithFormat:@"自采：%ld件   自营：%ld件",amountOne,amountTwo];
    [titleLabel sizeToFit];
    
    UILabel *numberLabel = [[UILabel alloc] init];
    [view addSubview:numberLabel];
    numberLabel.frame = CGRectMake(SCREENWIDTH-200-15, 19, 200, 14);
    numberLabel.text = [NSString stringWithFormat:@"共%ld件",totalCount];
    numberLabel.textAlignment = 2;
    numberLabel.textColor = RGBACOLOR(153, 153, 153, 1);
    numberLabel.font = FontWithSize(12);
    
    return view;
}

- (UIView *)tableViewFoot
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 0.01)];
    return view;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [self.myTableView tableViewDisplayWitMsg:@"您还没有上架任何自营商品" ifNecessaryForRowCount:self.dataArray.count withBottonTitle:@"去上架"];
    __weak DealerController *myself = self;
    self.myTableView.myBlcok = ^(int index)
    {
        StorageShoppingVC *storageVC = [[StorageShoppingVC alloc]init];
        storageVC.hidesBottomBarWhenPushed = YES;
        [myself.navigationController pushViewController:storageVC animated:YES];
    };
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StorageShoppingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StorageShoppingCell"];
    cell.index = 1;
    MainModel *model = self.dataArray[indexPath.row];
    [cell setCellWithMode:model];
    
    cell.editBtn.indexPath = indexPath;
    cell.delectBtn.indexPath = indexPath;
    cell.putawayBtn.indexPath = indexPath;
    
    [cell.editBtn addTarget:self action:@selector(editBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //下架
    [cell.delectBtn addTarget:self action:@selector(soldOutBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //分享
    [cell.putawayBtn addTarget:self action:@selector(sharkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)editBtnClick:(UIButton *)sender
{
    MainModel *model = self.dataArray[sender.indexPath.row];
    NSLog(@"编辑商品");
    EditGoodsController *editVC = [[EditGoodsController alloc] init];
    editVC.index = 1;
    editVC.model = model;
    editVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark - 在这个界面是下架
- (void)soldOutBtnClick:(UIButton *)sender
{
    NSLog(@"在这个界面是下架");
    MYHAleartView *alertView = [[MYHAleartView alloc] initMecommendAlertViewWithMessage:@"确认要下架该商品吗？" fuText:@"" sureBtnTitle:@"确认下架" cancleBtnTitle:@"保留商品"];
    [alertView showAlertView];
    
    MainModel *model = self.dataArray[sender.indexPath.row];
    NSInteger index = sender.indexPath.row;
    __weak DealerController *myself = self;
    
    alertView.sureBlock = ^(id  _Nonnull sender)
    {
        NSLog(@"确认下架");
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.product_id forKey:@"itemId"];
        [dic setValue:@"0" forKey:@"state"];
        
        [HttpRequest formPostPath:UpdateShoppingState_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
        {
            if (msgModel.status == 200)
            {
                [myself.dataArray removeObjectAtIndex:index];
                [myself.myTableView reloadData];
            }
        }];
    };
}

#pragma mark - 这个界面是分享
- (void)sharkBtnClick:(UIButton *)sender
{
    NSLog(@"这个界面是分享");
    MainModel *model = self.dataArray[sender.indexPath.row];
    //前往分享商品视图
    SharkShoppingVC *shopping = [[SharkShoppingVC alloc] init];
    shopping.hidesBottomBarWhenPushed = YES;
    shopping.product_id = model.product_id;
    shopping.isHide = YES;//自营隐藏
    [self.navigationController pushViewController:shopping animated:YES];
}


@end
